//
//  CustomMapView.m
//  Runner
//
//  Created by 张峰 on 2019/12/21.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//

#import "CustomMapView.h"
#import <CoreLocation/CoreLocation.h>
#import "NSObject+Tools.h"
#import "LocationModel.h"
#import "CustomAnnotation.h"
#import "MapViewFactory.h"

@interface CustomMapView()<MKMapViewDelegate, CLLocationManagerDelegate>
@property(nonatomic,strong)MKMapView *mapView;
@property(nonatomic,strong)CLLocationManager *locationManager;
@property(nonatomic,strong)NSMutableArray *coordinateArray;
@property(nonatomic,strong)NSMutableArray *annotationsArray;
@end

@implementation CustomMapView{
    //FlutterIosTextLabel 创建后的标识
    int64_t _viewId;
    //消息回调
    NSObject<FlutterBinaryMessenger> *_messenger;
}

-(instancetype)initWithWithFrame:(CGRect)frame
                  viewIdentifier:(int64_t)viewId
                       arguments:(id)args
                 binaryMessenger:(NSObject<FlutterBinaryMessenger> *)messenger{
    if ([super initWithFrame:frame]) {
        _messenger = messenger;
        _viewId = viewId;
        
        if (frame.size.width == 0) {
            frame = [UIScreen mainScreen].bounds;
        }
        [self flutterParameters:args];
        //开始定位
        [self.locationManager startUpdatingLocation];
    }
    return self;
    
}

- (void)flutterParameters:(id)args{
    if ([args isKindOfClass:[NSDictionary class]]) {
        NSDictionary *params = (NSDictionary *)args;
        NSString *coordinateJsonString = [params objectForKey:@"coordinates"];
        if (coordinateJsonString.length>0) {//解析经纬度信息
            id result = [NSObject objectFromJsonString:coordinateJsonString];
            if ([result isKindOfClass:[NSArray class]]) {
                NSArray *corArray = (NSArray *)result;
                for (NSDictionary *coordinateParam in corArray) {
                    [self.coordinateArray addObject:[LocationModel modelFromDict:coordinateParam]];
                }
            }
        }
    }
}

#pragma get/set

- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:self.frame];
        _mapView.delegate = self;
    }
    return _mapView;
}

- (NSMutableArray *)coordinateArray{
    if (!_coordinateArray) {
        _coordinateArray = [NSMutableArray new];
    }
    return _coordinateArray;
}

- (CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}

#pragma 地图标注处理
//添加标注
- (void)addAnotations{
    if (_annotationsArray.count>0) {
        [self.mapView removeAnnotations:_annotationsArray];
    }
    _annotationsArray = [NSMutableArray new];
    for (LocationModel *model in self.coordinateArray) {
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
        /* Create the annotation using the location */
        CustomAnnotation *annotation =[[CustomAnnotation alloc] initWithCoordinates:location title:model.name];
        [_annotationsArray addObject:annotation];
    }
    if (_annotationsArray.count>0) {
        [self.mapView addAnnotations:_annotationsArray];
    }
}

#pragma FlutterPlatformView

- (void)sendMessagrtoFlutter:(NSDictionary *)annotation{
    FlutterBasicMessageChannel* messageChannel = [FlutterBasicMessageChannel messageChannelWithName:@"messageChannelName" binaryMessenger:_messenger];
    // 组装消息
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:annotation 
                                                       options:NSJSONWritingPrettyPrinted 
                                                         error:&error];
    NSString *jsonString;
    if (jsonData) {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        [messageChannel sendMessage:(jsonString) reply:^(id reply) {
            NSLog(@"%@", reply);
        }];
    }
}

- (nonnull UIView*)view {
    return self.mapView;
}

//flutter调用OC的方法
-(void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result{
    if ([[call method] isEqualToString:@"flutterCallMethodName"]) {
        __weak __typeof__(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.view.backgroundColor = [UIColor blueColor];
        });
    } else {
        result(FlutterMethodNotImplemented);
    }
}


#pragma MKMapViewDelegate
//选中标注
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    NSDictionary *params =@{@"lat":@(view.annotation.coordinate.latitude),
                            @"lng":@(view.annotation.coordinate.longitude),
                            @"title":view.annotation.title};
    [self sendMessagrtoFlutter:params];
}

//取消选中标注
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view{
    NSLog(@"%s",__func__);
}

#pragma CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *loc = [locations firstObject];
    if (loc) {
        [self.locationManager stopUpdatingLocation];
        [self addAnotations];
    }else{
        return;
    }
    //维度：loc.coordinate.latitude
    //经度：loc.coordinate.longitude
    MKCoordinateSpan span = MKCoordinateSpanMake(0.5, 0.5);
    MKCoordinateRegion region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(loc.coordinate.latitude, loc.coordinate.longitude), span);
    [self.mapView setRegion:region];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"定位失败" message:error.localizedDescription preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertControl addAction:action];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertControl animated:YES completion:^{
    }];
}
@end
